package com.example.post.services.impl;
import com.example.post.mapper.BlogMapper;
import com.example.post.model.Blog;
import com.example.post.services.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
@Service
public class BlogServiceImpl implements BlogService {

    private final BlogMapper blogMapper;

    @Autowired
    public BlogServiceImpl(BlogMapper blogDao) {
        this.blogMapper = blogDao;
    }

    @Override
    public Blog getPostById(int id) {
        return blogMapper.findById(id).orElse(null);

    }

    @Override
    public List<Blog> getPostsByTitle(String title) {
        return blogMapper.findAllByTitleContaining(title);
    }

    @Override
    public void createPost(String title, String content, int userId) {
        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        blog.setCreateDate(LocalDateTime.now());
        blog.setUserId(userId);
        blogMapper.save(blog);
    }

    @Override
    public List<Blog> getAllBlogs() {
        return blogMapper.findAll();
    }

    @Override
    public void deletePost(int id) {
        blogMapper.deleteById(id);
    }

    @Override
    public List<Blog> getPostsByUserId(int userId) {
        return blogMapper.findAllByUserId(userId);
    }

    @Override
    @Transactional
    public void updateContentById(int id, String content) {
        blogMapper.updateContentById(id, content);
    }


}
